package Node;

import java.net.Socket;
import java.util.Random;

import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransportException;
import org.ini4j.Ini;

public class TransportLayer extends TSocket{
	
	private int currentBufferLen;
	private int dropRate; // 0 - 100
	private String processID;
	
	
	private void init(Ini serviceConfig){
		Ini.Section section = serviceConfig.get("Process");
		processID =  section.get("ProcessID");
		
		section = serviceConfig.get("HeartBeatClient");
		dropRate =  Integer.parseInt(section.get("MessageDropRate"));
		
		currentBufferLen = 0;
		
	}
	
	/**
	* Creates a new unconnected socket that will connect to the given host
	* on the given port.
	*
	* @param host Remote host
	* @param port Remote port
	*/
	public TransportLayer(String host, int port, Ini serviceConfig) {
		super(host, port, 0);
		
		init(serviceConfig);

	}
	
	public TransportLayer(Socket socket, Ini serviceConfig) throws TTransportException {
		super(socket);
		
		init(serviceConfig);

	}
	
	@Override
	public void write(byte[] buf, int off, int len) throws TTransportException {
	    currentBufferLen += len;
	    super.write(buf, off, len);
	}
	
	@Override
	public void flush() throws TTransportException {
		
		Random generator = new Random();
		int r = generator.nextInt();
		if(Math.abs(r) % 100 >= dropRate){
			System.out.println("Process " + processID + " Sending message: " + currentBufferLen + " bytes");
			super.flush();
		}
		else{
			System.out.println("Process " + processID + " dropping message from " + processID);
		}
		currentBufferLen = 0;
		
	}
}